package com.boy.rpc.framework.console.service;

import com.boy.rpc.framework.console.Constant;
import com.boy.rpc.framework.console.bean.RedisConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Set;

/**
 * Created by wesley on 2017-03-13.
 */
@Deprecated
public class RedisService {

    private static final Logger logger = LoggerFactory.getLogger(RedisService.class);

    private static JedisPool jedisPool = null;


    public RedisService(RedisConfig redisConfig) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(Constant.REDIS_MAX_IDLE);
        config.setMaxWaitMillis(Constant.REDIS_MAX_WAIT);
        jedisPool = new JedisPool(config, redisConfig.getRedisAddress(), redisConfig.getRedisPort(), Constant.REDIS_CONNECTION_TIMEOUT, redisConfig.getRedisPassword());
        logger.debug("RedisService instantiation!");
    }

    public static Jedis getJedis(){
        logger.debug("RedisService getJedis start!");
        Jedis jedis = null;
        try {
            if (jedisPool != null) {
                jedis = jedisPool.getResource();
            }
        } catch (Exception e) {
            logger.error("RedisService getJedis fail"+e);
        }
        logger.debug("RedisService getJedis end!");
        return jedis;
    }


    /**
     * 释放jedis资源
     */
    public static void releaseJedis(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    public Set<String> getAllKeys() {
        Jedis jedis = getJedis();
        try {
            return jedis.keys("com.boy.rpc.framework.*");
        }catch (Exception e) {
            logger.error("RedisService getAllKeys fail" + e);
        }finally {
            releaseJedis(jedis);
        }
        return null;
    }
}
